<?php
include('class.db.php');

date_default_timezone_set('UTC');

class Register{
	private $_username;
	private $_name;
	private $_first;
	private $_last;
	private $_password;
	private $_passmd5;
	private $_rights;
	private $_register;
	private $_currenttime;
	
	private $_errors;
	private $_token;
	
	public function __construct(){
		$this->_register = isset($_POST["register"]);
		$this->_errors	 = array();
		$this->_username = $this->filter($_POST["ruser"]);
		$this->_password = $this->filter($_POST["rpass"]);
		$this->_rights	 = $_POST["rights"];
		
		if($this->_rights == "Instructeur"){
			$this->_rights = "1";
		}
		
		if($this->_rights == "Cursist"){
			$this->_rights = "0";
		}
		
		$this->_token	 = $_POST["token"];
		
		$this->_name	 = explode(".",$this->_username);
		$this->_first	 = $this->_name[0];
		$this->_last	 = $this->_name[1];
		
		$this->_passmd5	 = md5($this->_password);
		
		$this->_currenttime = date(DATE_ATOM);
		
	}
	
	public function process(){
		if($this->validToken() && $this->validData()){
			$this->register();
		}
		if(count($this->_errors) > 0){
			return false;
		}
		else{
			return true;
		}
	}
	
	public function filter($var){
		return preg_replace("/[^a-zA-z0-9@.]/","",$var);
	}
	
	public function register(){
		//Database Connection Data
		$db = new db();
		$sql = "INSERT INTO users (username,first,last,password,rights,register) VALUES ('$this->_username','$this->_first','$this->_last','$this->_passmd5','$this->_rights','$this->_currenttime')";
		$database = "vdab";
		
		$result = $db->query($database, $sql);
	
		if($result){
			return true;
		}else {
			return false;
			$this->_errors[] = "Could not process query";
		}
	}
	
	public function showErrors(){
		"Errors:<br>";
		foreach($this->_errors as $key=>$value)
		  echo $value."<br>";
	}
	
	public function validData(){
		if(empty($this->_username)){
			$this->_errors[] = "Invalid username";
		}
		if(empty($this->_password)){
			$this->_errors[] = "Invalid password";
		}
		if(count($this->_errors) > 0){
			return false;
		}
		else{
			return true;
		}
	}
	
	public function validToken(){
		if(!isset($_SESSION["token"]) || $this->_token != $_SESSION["token"]){
			$this->_errors[] = "Invalid submission";
		}
		if(count($this->_errors) > 0){
			return false;
		}
		else{
			return true;
		}
	}
}
?>